package aiUtils;

import org.json.JSONObject;
import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AiUtils {

    // 定义API请求信息
    String apiUrl = "https://api.siliconflow.cn/v1/chat/completions";
    String apiKey = "Bearer sk-kaesinrznecqdxxrktbzkayotmhbybpddfdqvnjgdeylxxiy";

    public String askAi(String projectName,String workType){
        String result = "有问题";

        // 定义提示词(System Role)
        String systemPrompt = "# 角色:智能周报编写助手\n" +
                "\n" +
                "## 背景:\n" +
                "根据项目名称，编写符合工作类比的工作内容\n" +
                "\n" +
                "## Profile：\n" +
                "- Language: 中文\n" +
                "- Description: 按照工作类别，编写工作内容\n" +
                "\n" +
                "## 技能:\n" +
                "- 善于展开关键词,补充相关内容\n" +
                "\n" +
                "## 目标:\n" +
                "- 根据提给定的工作类别，编写工作内容\n" +
                "- 工作内容尽量扩充详细\n" +
                "\n" +
                "## 工作流程:\n" +
                "1. 工作类别为：" + workType + "\n" +
                "2. 获取项目名称\n" +
                "3. 编写出符合工作类别的工作内容\n" +
                "\n" +
                "##约束\n" +
                "输出内容只要3条\n" +
                "输出内容不得超过180字，每一小条工作内容接近60字\n" +
                "输出内容不得出现确保话术：“确保xxxxxx”之类的话不得出现\n" +
                "\n" +
                "## 输出格式:\n" +
                "\n" +
                "1、工作事项\n" +
                "2、工作事项\n" +
                "3、工作事项\n" +
                "\n" +
                "## 建议:\n" +
                "- 严格按照给出的格式输出，只需要1、2、3，不要“一，二，三”\n" +
                "- 内容尽量口语化，避免过于书面\n" +
                "- 输出内容不得超过180字，每一小条工作内容接近60字\n" +
                "- 输出内容不得出现确保话术：“确保xxxxxx”之类的话不得出现\n" +
                "- 内容中不要出现具体的金额数字以及百分比进度\n" +
                "- 只需要输出工作内容文字，不需要“工作事项”的开场标题\n" +
                "- 最后不需要思考过程和总结语";



        try {
            // 构造请求体JSON
            JSONObject payload = new JSONObject();
            payload.put("model", "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B");

            JSONArray messages = new JSONArray();
            messages.put(new JSONObject().put("role", "system").put("content", systemPrompt));
            messages.put(new JSONObject().put("role", "user").put("content", projectName));

            payload.put("messages", messages);
            payload.put("temperature", 0.3);
            payload.put("max_tokens", 2000);

            // 创建HTTP连接
            HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", apiKey);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = payload.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    // 解析JSON响应
                    JSONObject jsonResponse = new JSONObject(response.toString());
                    JSONArray choices = jsonResponse.getJSONArray("choices");
                    String aiResponse = choices.getJSONObject(0)
                            .getJSONObject("message")
                            .getString("content");

                    //输出结果
//                    System.out.println(aiResponse);
                    result = aiResponse;
                }
            } else {
                System.out.println("❌ 请求失败，状态码：" + responseCode);
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        errorResponse.append(responseLine.trim());
                    }
                    System.out.println("错误响应: " + errorResponse);
                }
            }
        } catch (Exception e) {
            System.out.println("发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        AiUtils aiUtils = new AiUtils();
        String projectName = "滨湖区卫生健康委员会滨湖区电子票据一体化平台信息管理系统运维项目";
        String workType = "项目整体进展管理；项目立项、项目合同签订、后向采购文件编制；项目客户对接，实施、评审、现场勘察设计；项目竣工验收工作等";
        aiUtils.askAi(projectName,workType);
    }
}
